<template>
	<div class="input">
		<input type="text" v-model="text" placeholder="修改图片链接" />
		<button @click="changeImage">完成</button>
	</div>
	<div class="bodypix">
		<div class="show">
			<img id="img" :src="imgsrc" crossorigin="anonymous" />
			<canvas id="canvas" v-show="ready"></canvas>
		</div>
	</div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from "vue";

function runBodyPix(callback?: () => any) {
	const image = document.getElementById("img");
	const canvas = document.getElementById("canvas");

	function drawMask(segmentation: any) {
		const opacity = 0.7;
		const maskBlurAmount = 0;
		const flipHorizontal = false;
		const mask = window.bodyPix.toMask(segmentation);
		if (callback) {
			callback();
		}
		window.bodyPix.drawMask(
			canvas,
			image,
			mask,
			opacity,
			maskBlurAmount,
			flipHorizontal
		);
	}

	async function loadAndPredict() {
		const net = await window.bodyPix.load();
		const segmentation = await net.segmentPerson(image);

		drawMask(segmentation);
	}

	loadAndPredict();
}

export default defineComponent({
	name: "bodypix",
	setup() {
		const text = ref("");
		const ready = ref(false);
		const imgsrc = ref("/origin.png");

		onMounted(() => {
			runBodyPix(() => (ready.value = true));
		});

		function changeImage() {
			if (text.value.length === 0) {
				imgsrc.value = "/origin.png";
			} else {
				imgsrc.value = text.value;
			}

			ready.value = false;

			runBodyPix(() => (ready.value = true));
		}

		return {
			text,
			imgsrc,
			ready,
			changeImage,
		};
	},
});
</script>

<style lang="less">
.input {
	width: 100%;
	display: flex;
	justify-content: center;
	margin: 20px 0px;
	input {
		width: 500px;
		outline-style: none;
		border: 1px solid #ccc;
		border-radius: 3px;
		padding: 10px;
		font-size: 14px;
	}
}
.bodypix {
	display: flex;
	justify-content: center;
	.show {
		transform: scale(0.7) translateY(-120px);
	}
}
</style>
